﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BitPortal.Models;
using BitPortal.Business;
using BitPortal.Utils;
using Ext.Net;
using System.Web.Security;

namespace BitPortal.Admin.Service.Work.Module
{
    public partial class WorkAddEdit : Controls.BaseAdminControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            //ExtendedBitPortalEntities ent = new ExtendedBitPortalEntities();
            //IQueryable<Models.aspnet_Users> list = from pp in ent.aspnet_Users
            //                                       orderby pp.UserName ascending
            //                                       select pp;

            //foreach (Models.aspnet_Users item in list)
            //{
            //    UserBLL.GetByRole("Employee", false);
            //    Ext.Net.ListItem node = new Ext.Net.ListItem(item.UserName, item.UserId.ToString());
            //    this.cbxEmployees.Items.Add(node);
            //    this.cbxManager.Items.Add(node);

            //}

            this.employeeSelecter2.ComboBoxUser.FieldLabel = "Người quản lý";
            
        }

        /// <summary>
        /// bind du lieu vao trong wordaddedit
        /// </summary>
        /// <param name="workI"></dparam>


        public void BindData(long workId = 0)
        {
            if (workId > 0)
            {
                BitPortal.Models.WorkWarranty work = WorkWarrantyBLL.GetByWorkID(workId);
                if (work != null)
                {
                    txtworkID.Text = work.WorkWarrantyID.ToString();
                    txterrorID.Text = work.ErrorID.ToString();
                    //txtuserID.Text = work.UserId.ToString();

                    txtWorkName.Text = work.WorkName;
                    txtDescOfManager.Text = work.DescOfManager.ToClearnString();
                    txtDescOfEmployee.Text = work.DescOfEmployee.ToClearnString();
                    txtDescOfCustomer.Text = work.ErrorReport.DesOfCustomer.ToClearnString();
                    txtComment.Text = work.Comment;
                    cbkSure.Checked = (Boolean)work.IsDescSure;
                    if (work.DateReport != null)
                    {
                        datetimeReport.Value = work.DateReport;
                    }
                    if (work.DateRequired != null)
                    {
                        dateRequire.Value = work.DateRequired;
                    }
                    if (work.DateManagerConfirm != null)
                    {
                        dateManagerConfirm.Value = work.DateManagerConfirm;
                    }
                    if (work.DateFixed != null)
                    {
                        dateFixed.Value = work.DateFixed;
                    }
                    if (work.DateFinished != null)
                    {
                        dateFinished.Value = work.DateFinished;
                    }
                    //cbxState.Text=BindState(work.StateWork);

                    txtExpense.Text = work.Expense.ToString();
                    cbxStateWork.SelectedItem.Value = work.StateWork.ToString();
                    cbxPriority.SelectedItem.Value = work.Priority.ToString();
                    txtUserRepair.Text = work.UsersRepair;

                    
                    
                   

                    //Panel1.Selectable = true;
                    btnInsert.Hidden = true;
                   
                    Window1.Show();
                }
            }

            else
            {
                Window1.Show();

            }
        }
      
       
        
        /// <summary>
        /// them doi tuong cong viec moi 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnInsert_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("WorkInsert",useExceptionHandler:true);
                string userRepair = "";
                
                BitPortal.Models.WorkWarranty work = new Models.WorkWarranty()
                {
                    ErrorID = Convert.ToInt64(txterrorID.Text),
                    UserId = new Guid(UserBLL.GetUserByNameOrEmail(employeeSelecter1.ComboBoxUser.Text).ProviderUserKey.ToString()),
                    NoteGroupId=NoteGroupBLL.InsertNoteGroup(),


                    WorkName = txtWorkName.Text,
                    DescOfManager = txtDescOfManager.Text,
                    DescOfEmployee = txtDescOfEmployee.Text,
                    IsDescSure = cbkSure.Checked,
                    Comment = txtComment.Text,

                    DateReport = datetimeReport.Text.ToDateTimeTryParse(),
                    DateCustomerConfirm = dateCustomerConfirm.Text.ToDateTimeTryParse(),
                    DateManagerConfirm = dateManagerConfirm.Text.ToDateTimeTryParse(),
                    DateFixed = dateFixed.Text.ToDateTimeTryParse(),
                    DateFinished = dateFinished.Text.ToDateTimeTryParse(),
                    DateRequired = dateRequire.Text.ToDateTimeTryParse(),


                    Expense = txtExpense.Text.ToInt64TryParse(),
                    Priority = Convert.ToInt32(cbxPriority.SelectedItem.Value),
                    StateWork=Convert.ToInt32(cbxStateWork.SelectedItem.Value),
                    IsDeleted=false,
                    UsersRepair = txtUserRepair.Text,

                };


                
                int index = work.Insert();
                if (index > 0)
                {
                    (this.Page as Controls.BaseAdminPage).ShowNotification("Thêm công việc thành công");
                    ClearAll();
                    Window1.Hide();
                    ReloadTargetData();
                    try
                    {
                        Utils.EmailUtils.SendEmail(PortalConfigBLL.GetValueByName("DefaultAdminEmail").ToString(),
                        UserBLL.GetMailForWork(employeeSelecter1.ComboBoxUser.Text,employeeSelecter2.ComboBoxUser.Text),
                        PortalConfigBLL.GetValueByName("Template.EmailCreateWork.Header").ToString(),
                        PortalConfigBLL.GetValueByName("Template.EmailCreateWork.Body").ToString().Replace("{WorkName}", txtWorkName.Text).Replace("{UsersRepair}", userRepair)
                        );
                        (this.Page as Controls.BaseAdminPage).ShowNotification("Đã gửi mail thông báo công việc thành công");
                    }
                    catch (System.Exception ex)
                    {
                        (this.Page as Controls.BaseAdminPage).ShowNotification("Có lỗi khi gưỉ mail cho người quản lý công việc");
                    }

                }

            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }
            
        }
        /// <summary>
        /// luu lai thong tin doi tuong cong viec
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("WorkEdit",useExceptionHandler:true);
               
                
                long ID = Convert.ToInt64(txtworkID.Text);
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                BitPortal.Models.WorkWarranty work = bitEnt.WorkWarranties.SingleOrDefault(ent => ent.WorkWarrantyID == ID);
                if (work != null)
                {
                    
                    work.WorkName = txtWorkName.Text.Trim();
                    work.DescOfManager = txtDescOfManager.Text;
                    work.DescOfEmployee = txtDescOfEmployee.Text;
                    work.IsDescSure = cbkSure.Checked;
                    work.Comment = txtComment.Text;

                    work.DateReport = datetimeReport.Text.ToDateTimeTryParse();
                    work.DateManagerConfirm = dateManagerConfirm.Text.ToDateTimeTryParse();
                    work.DateFixed = dateFixed.Text.ToDateTimeTryParse();
                    work.DateCustomerConfirm = dateCustomerConfirm.Text.ToDateTimeTryParse();
                    work.DateFinished = dateFinished.Text.ToDateTimeTryParse();
                    work.DateRequired = dateRequire.Text.ToDateTimeTryParse();

                    work.Expense = txtExpense.Text.ToInt64TryParse();
                    work.UsersRepair = employeeSelecter2.ComboBoxUser.Text;
                    work.Priority = Convert.ToInt32(cbxPriority.SelectedItem.Value);
                    work.StateWork = Convert.ToInt32(cbxStateWork.SelectedItem.Value);
                    work.IsDeleted = false;

                    
                    
                }

                int index = bitEnt.SaveChanges();
                if (index > 0)
                {
                    (this.Page as Controls.BaseAdminPage).ShowNotification("Cập nhật bài viết thành công!");
                    ClearAll();
                    Window1.Hide();
                    ReloadTargetData();
                }
            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }
            

        }

        public void BindDataFromError(long errorId)
        {
            if (errorId > 0) 
            {
                ExtendedBitPortalEntities ent = new ExtendedBitPortalEntities();

                ErrorReport error = ent.ErrorReports.SingleOrDefault(pp => pp.ErrorID == errorId);

                this.txtDescOfCustomer.Text = error.DesOfCustomer.ToClearnString();
                this.datetimeReport.Value = error.DateReport;
                this.txterrorID.Text = errorId.ToString();
                btnUpdate.Hidden = true;
                Window1.Show();
            }
        }


        public void ClearAll()
        {
            this.txterrorID.Clear();
            this.dateCustomerConfirm.Clear();
            this.dateFinished.Clear();
            this.dateFixed.Clear();
            this.dateManagerConfirm.Clear();
            this.dateRequire.Clear();
            this.datetimeReport.Clear();
            this.txtComment.Clear();
            this.txtDescOfCustomer.Clear();
            this.txtDescOfEmployee.Clear();
            this.txtDescOfManager.Clear();
            this.txtNoteGroupId.Clear();
            this.txtUserRepair.Clear();
            this.txtworkID.Clear();
            this.txtWorkName.Clear();
            

        }

        public void btnAdd_Click(object sender, DirectEventArgs e)
        {
            this.txtUserRepair.Text += employeeSelecter2.ComboBoxUser.Text + " ,";
        }
        
        
    }
}